package placa;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author jose.silva
 */
public class TelaPlaca extends javax.swing.JFrame {

    /**
     * Creates new form TelaPlaca
     */
   
    public TelaPlaca() {
        initComponents();
        populaGridComConsulta(listAll());
        btRemover.setEnabled(false);
        btAlterar.setEnabled(false);
        btGravar.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelPlaca = new javax.swing.JLabel();
        tfPlaca = new javax.swing.JFormattedTextField();
        labelMarca = new javax.swing.JLabel();
        labelModelo = new javax.swing.JLabel();
        tfModelo = new javax.swing.JTextField();
        labelValor = new javax.swing.JLabel();
        tfValor = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaDados = new javax.swing.JTable();
        labelPesquisa = new javax.swing.JLabel();
        tfPesquisa = new javax.swing.JTextField();
        cbTipoPesquisa = new javax.swing.JComboBox();
        tfMarca = new javax.swing.JTextField();
        btInserir = new javax.swing.JButton();
        btRemover = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btPesquisar = new javax.swing.JButton();
        btGravar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cadastro de veículos");
        setResizable(false);

        labelPlaca.setText("Placa:");

        tfPlaca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfPlacaActionPerformed(evt);
            }
        });

        labelMarca.setText("Marca:");

        labelModelo.setText("Modelo:");

        labelValor.setText("Valor:");

        tabelaDados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Placa", "Marca", "Modelo", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaDados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaDadosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaDados);

        labelPesquisa.setText("Pesquisa:");

        cbTipoPesquisa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Placa", "Marca", "Modelo" }));
        cbTipoPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbTipoPesquisaActionPerformed(evt);
            }
        });

        btInserir.setText("Inserir");
        btInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btInserirActionPerformed(evt);
            }
        });

        btRemover.setText("Remover");
        btRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRemoverActionPerformed(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        btGravar.setText("Gravar");
        btGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGravarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelPlaca)
                            .addComponent(labelValor))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfValor, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
                            .addComponent(tfPlaca))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(39, 39, 39)
                                .addComponent(btInserir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btRemover)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btAlterar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btGravar)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelMarca)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tfMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(labelModelo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tfModelo))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(labelPesquisa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btPesquisar)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelPlaca)
                    .addComponent(tfPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelMarca)
                    .addComponent(labelModelo)
                    .addComponent(tfModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelValor)
                    .addComponent(tfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btInserir)
                    .addComponent(btRemover)
                    .addComponent(btAlterar)
                    .addComponent(btGravar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelPesquisa)
                    .addComponent(tfPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPesquisar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        
    private void tfPlacaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfPlacaActionPerformed
        

        
    }//GEN-LAST:event_tfPlacaActionPerformed

    private void btInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btInserirActionPerformed
        // TODO add your handling code here:
        cadastrar();
        
    }//GEN-LAST:event_btInserirActionPerformed

    private void btRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRemoverActionPerformed

        DefaultTableModel tbDados = (DefaultTableModel) tabelaDados.getModel();
        tbDados.removeRow(tabelaDados.getSelectedRow());
        limpar();
        btPesquisar.setEnabled(tabelaDados.getRowCount()>0);
                
    }//GEN-LAST:event_btRemoverActionPerformed

    private void tabelaDadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaDadosMouseClicked
        // TODO add your handling code here:
        btRemover.setEnabled(true);
        btAlterar.setEnabled(true);
        btGravar.setEnabled(true);
    }//GEN-LAST:event_tabelaDadosMouseClicked

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
       
        alterar();
        btInserir.setEnabled(false);
        btRemover.setEnabled(false);
        
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGravarActionPerformed
        
        if(validar()){
            gravarAlteracao(tfPlaca.getText(), tfMarca.getText(), tfModelo.getText(), tfValor.getText());
            limpar();
        } else {
            JOptionPane.showMessageDialog(null, "Erro no cadastro, insira os valores corretamente.");
        }
    }//GEN-LAST:event_btGravarActionPerformed

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        List<Veiculo> veiculos = consulta(tfPesquisa.getText().toString(), cbTipoPesquisa.getSelectedItem().toString());
        populaGridComConsulta(veiculos);
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void cbTipoPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTipoPesquisaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbTipoPesquisaActionPerformed

    /**
     * @param args the command line arguments
     */
        
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPlaca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPlaca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPlaca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPlaca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        
               
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaPlaca().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btGravar;
    private javax.swing.JButton btInserir;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btRemover;
    private javax.swing.JComboBox cbTipoPesquisa;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelMarca;
    private javax.swing.JLabel labelModelo;
    private javax.swing.JLabel labelPesquisa;
    private javax.swing.JLabel labelPlaca;
    private javax.swing.JLabel labelValor;
    private javax.swing.JTable tabelaDados;
    private javax.swing.JTextField tfMarca;
    private javax.swing.JTextField tfModelo;
    private javax.swing.JTextField tfPesquisa;
    private javax.swing.JFormattedTextField tfPlaca;
    private javax.swing.JFormattedTextField tfValor;
    // End of variables declaration//GEN-END:variables

   
    private void cadastrar() {
        if (validar()) {
            inserir(tfPlaca.getText(), tfMarca.getText(), tfModelo.getText(), tfValor.getText());
            limpar();
        }
    }
    
    private void inserir(String placa, String marca, String modelo, String valor) {
        if (validar()){
            ArquivoTexto arquivoTexto = new ArquivoTexto();
            arquivoTexto.setPath("C:\\carro.txt");
            StringBuilder builder = new StringBuilder(placa+";"+marca+";"+modelo+";"+valor+";");
            arquivoTexto.gravar(builder.toString());
            criaTabela(tabelaDados);
            DefaultTableModel tbDados = (DefaultTableModel) tabelaDados.getModel();
            populaGridComConsulta(listAll());
            tabelaDados.setModel(tbDados);
        } else {
            JOptionPane.showMessageDialog(null, "Erro no cadastro, insira os valores corretamente.");
        }
        
    }
    
    private void limpar() {

        tfPlaca.setText("");
        tfMarca.setText("");
        tfModelo.setText("");
        tfValor.setText("");
        tfPlaca.requestFocus();
        
        btRemover.setEnabled(false);
        btGravar.setEnabled(false);
        btAlterar.setEnabled(false);
        btInserir.setEnabled(true);

    }
    
    private void alterar() {

        DefaultTableModel tbDados = (DefaultTableModel) tabelaDados.getModel();
        tfPlaca.setText(tabelaDados.getValueAt(tabelaDados.getSelectedRow(), 0).toString());
        tfMarca.setText(tabelaDados.getValueAt(tabelaDados.getSelectedRow(), 1).toString());
        tfModelo.setText(tabelaDados.getValueAt(tabelaDados.getSelectedRow(), 2).toString());
        tfValor.setText(tabelaDados.getValueAt(tabelaDados.getSelectedRow(), 3).toString());


    }
    
    private void gravarAlteracao(String placa, String marca, String modelo, String valor){
        ArquivoTexto arquivoTexto = new ArquivoTexto();
        arquivoTexto.setPath("C:\\carro.txt");
        arquivoTexto.gravar(placa+";"+marca+";"+modelo+";"+valor+";");
        String[] linha = {placa, marca, modelo, valor};
        DefaultTableModel tbDados = (DefaultTableModel) tabelaDados.getModel();
        tbDados.removeRow(tabelaDados.getSelectedRow());
        tbDados.addRow(linha);
        tabelaDados.setModel(tbDados);
        
    }
    
    private void inicia(){
        btGravar.setEnabled(false);
        btAlterar.setEnabled(false);
        btRemover.setEnabled(false);
    }
    
    private boolean validar() {
        
        return ((!tfPlaca.getText().trim().isEmpty())
                && (!tfMarca.getText().trim().isEmpty())
                && (!tfModelo.getText().trim().isEmpty())
                && (!tfValor.getText().trim().isEmpty())
                );       
    }
    
    private List<Veiculo> consulta(String consulta, String tpConsulta) {
        if (!isNullOrEmptyString(consulta)) {
            
            ArquivoTexto arquivoTexto = new ArquivoTexto();
            arquivoTexto.setPath("C:\\carro.txt");
            List<String> dados = arquivoTexto.carregar();
            List<Veiculo> veiculos = new ArrayList<Veiculo>();

            if (tpConsulta.equalsIgnoreCase("placa")) {

                for (String s : dados) {
                    if (s.contains(consulta)) {
                        String[] result = s.split(";");
                        Veiculo veiculo = new Veiculo();
                        veiculo.setPlaca(result[0]);
                        veiculo.setMarca(result[1]);
                        veiculo.setModelo(result[2]);
                        veiculo.setPreco(Double.parseDouble(result[3]));
                        veiculos.add(veiculo);
                        return veiculos;
                    }
                    
                }

            } else if (tpConsulta.equalsIgnoreCase("marca")) {

            } else if (tpConsulta.equalsIgnoreCase("modelo")) {

            }
        }
        return null;
    }
    
    private boolean isNullOrEmptyString(String string) {
        return "".equalsIgnoreCase(string) || null == string;
    }

    private void populaGridComConsulta(List<Veiculo> veiculos) {
            DefaultTableModel tbDados = (DefaultTableModel) tabelaDados.getModel();
            for (Veiculo v : veiculos) {
                String[] linha = {v.getPlaca(), v.getMarca(), v.getModelo(), String.valueOf(v.getPreco())};
                tbDados.addRow(linha);
            }
            tabelaDados.setModel(tbDados);
    }

    private List<Veiculo> listAll() {
            ArquivoTexto arquivoTexto = new ArquivoTexto();
            arquivoTexto.setPath("C:\\carro.txt");
            List<String> dados = arquivoTexto.carregar();
            List<Veiculo> veiculos = new ArrayList<Veiculo>();
            for (String s : dados) {
                String[] result = s.split(";");
                Veiculo veiculo = new Veiculo();
                veiculo.setPlaca(result[0]);
                veiculo.setMarca(result[1]);
                veiculo.setModelo(result[2]);
                veiculo.setPreco(Double.parseDouble(result[3]));
                veiculos.add(veiculo);
            }
            return veiculos;
    }
    
    private void criaTabela(JTable tabela) {
        tabela.setModel(
        new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Placa", "Marca", "Modelo", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
    }
    
}
